package com.graceplayer.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.Manifest;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.os.Handler;
import android.os.Message;

import android.annotation.TargetApi;
import android.app.Activity;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.media.TimedText;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.DialogPreference;
import android.provider.MediaStore;
import android.support.annotation.RequiresPermission;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.graceplayer.data.PropertyBean;
import android.widget.ProgressBar;

import com.graceplayer.data.Music;
import com.graceplayer.data.MusicList;
import com.graceplayer.service.MusicService;

public class MainActivity extends Activity {

	private ImageButton imgBtn_Previous;
	private ImageButton imgBtn_PlayOrPause;
	private ImageButton imgBtn_Stop;
	private ImageButton imgBtn_Next;
	private SeekBar progressBar;
	private TextView musicTimeText;
	private TextView playedTime;
	private TextView textView;
	private Menu menu;
	private Button menuBtn;
	private ListView list;
	private ArrayList<Music> musicArrayList;
    private MediaPlayer player = new MediaPlayer();
    private int status= MusicService.COMMAND_STOP;
    private StatusChangeReceiver receiver;
    private seekBarChangedReceiver receiver2;
    private musicChangedReceiver receiver3;
    private LinearLayout root_Layout;
    //这里的number不是用来记录当前正在播放的歌曲序号
	//而是用来记录用户手动选择的歌曲，然后发送给service，更改service中当前播放的歌曲序号
	private int number = 0;
	private int i=0;
	private static boolean isExit=false;

	private static final int MODE_LIST_SEQUENCE=0;
	private static final int MODE_SINGLE_CYCLE=1;
	private static final int MODE_LIST_CYCLE=2;
	private static final int MODE_RANDOM=3;
	private int playmode=MODE_LIST_SEQUENCE;

    private static int REQUEST_PERMISSION_CODE = 1;

	private TextView tv_vol;
	private SeekBar  seekbar_vol;

	private ImageView iv_sleep;
	private Timer timer_sleep ;
	private static final boolean NOTSLEEP = false;
	private static final boolean ISSLEEP = true;
	private int sleepminute = 20;
	private static boolean sleepmode=MainActivity.NOTSLEEP;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
			int hasWritePermission = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
			int hasReadPermission = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
			List<String> permissions=new ArrayList<>();
			if(hasWritePermission!= PackageManager.PERMISSION_GRANTED){
				permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
			}else{}
			if(hasReadPermission!=PackageManager.PERMISSION_GRANTED){
				permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
			}else{}
			if(!permissions.isEmpty()){
				ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},REQUEST_PERMISSION_CODE);
			}
		}
		findViews();
		registerListeners();
		initMusicList();
		initListView();
		checkMusicfile();
		bindStatusChangedReceiver();
		startService(new Intent(this,MusicService.class));
	}
	private void setTheme(String theme){
		if("彩色".equals(theme)){
			root_Layout.setBackgroundResource(R.drawable.bg_color);
		}else if("花朵".equals(theme)){
			root_Layout.setBackgroundResource(R.drawable.bg_digit_flower);
		}else if("群山".equals(theme)){
			root_Layout.setBackgroundResource(R.drawable.bg_mountain);
		}else if("小狗".equals(theme)){
			root_Layout.setBackgroundResource(R.drawable.bg_running_dog);
		}else if("冰雪".equals(theme)){
			root_Layout.setBackgroundResource(R.drawable.bg_snow);
		}else if("女孩".equals(theme)){
			root_Layout.setBackgroundResource(R.drawable.bg_music_girl);
		}else if("朦胧".equals(theme)){
			root_Layout.setBackgroundResource(R.drawable.bg_blur);
		}
	}
	public boolean onCreateOptionsMenu(Menu menu){
		this.getMenuInflater().inflate(R.menu.main,menu);
		return true;
	}
	public boolean onOptionsItemSelected(MenuItem item){
		switch (item.getItemId()){
			case R.id.menu_theme:
				new AlertDialog.Builder(this)
						.setTitle("请选择主题")
						.setItems(R.array.theme,new DialogInterface.OnClickListener(){
							public void onClick(DialogInterface dialog,int which) {
								//Log.d("主题",String.valueOf(PropertyBean.THEMES));
								PropertyBean property=new PropertyBean(MainActivity.this);
								String theme = PropertyBean.THEMES[which];
								MainActivity.this.setTheme(theme);
								property.setAndSaveTheme(theme);
							}
						}).show();
				break;
			case R.id.menu_playmode:
				String[] mode=new String[] {"顺序播放","单曲循环","列表循环","随机播放"};
				AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
				builder.setTitle("播放模式");
				builder.setSingleChoiceItems(mode, playmode, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialogInterface, int i) {
						playmode=i;
					}
				});
				builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialogInterface, int i) {
						switch (playmode){
							case 0:
								playmode=MainActivity.MODE_LIST_SEQUENCE;
								Toast.makeText(getApplicationContext(),"顺序播放",Toast.LENGTH_SHORT).show();
								break;
							case 1:
								playmode=MainActivity.MODE_SINGLE_CYCLE;
								Toast.makeText(getApplicationContext(),"单曲循环",Toast.LENGTH_SHORT).show();
								break;
							case 2:
								playmode=MainActivity.MODE_LIST_CYCLE;
								Toast.makeText(getApplicationContext(),"列表循环",Toast.LENGTH_SHORT).show();
								break;
							case 3:
								playmode=MainActivity.MODE_RANDOM;
								Toast.makeText(getApplicationContext(),"随机播放",Toast.LENGTH_SHORT).show();
								break;
							default:
								break;
						}
					}
				});
				builder.show();
				break;
			case R.id.menu_sleep:
				showSleepDialog();
				break;
			case R.id.menu_about:
				new AlertDialog.Builder(MainActivity.this)
						.setTitle("GRacePlayer")
						.setMessage(R.string.about2).show();
				break;
			case R.id.menu_quit:
				new AlertDialog.Builder(this)
						.setTitle("提示")
						.setMessage("退出").setPositiveButton("确定",new android.content.DialogInterface.OnClickListener(){
							public void onClick(DialogInterface arg0,int arg1){
							    System.exit(0);
                            }
				}).show();
				break;
		}
		return super.onOptionsItemSelected(item);
	}
	private void findViews() {
		imgBtn_Previous = (ImageButton) findViewById(R.id.imageButton1);
		imgBtn_PlayOrPause = (ImageButton) findViewById(R.id.imageButton2);
		imgBtn_Stop = (ImageButton) findViewById(R.id.imageButton3);
		imgBtn_Next = (ImageButton) findViewById(R.id.imageButton4);
		progressBar=(SeekBar) findViewById(R.id.progressBar2);
		musicTimeText=(TextView) findViewById(R.id.musicTime);
		playedTime=(TextView) findViewById(R.id.playedTime);
		list = (ListView) findViewById(R.id.listView1);
		textView=(TextView) findViewById(R.id.textView);
		root_Layout=(LinearLayout) findViewById(R.id.linearLayout);
		menuBtn=(Button) findViewById(R.id.menuBtn);
		tv_vol = (TextView)findViewById(R.id.main_tv_volumeText);
		seekbar_vol = (SeekBar)findViewById(R.id.main_sb_volumebar);
		iv_sleep = (ImageView)findViewById(R.id.main_iv_sleep);
	}
    private void registerListeners() {
		imgBtn_Previous.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				/*
				moveNumberToPrevious();
				play(number);
				*/
				imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
				if(playmode==MainActivity.MODE_RANDOM) sendBroadcastOnCommand(MusicService.COMMAND_RANDOM);
				else sendBroadcastOnCommand(MusicService.COMMAND_PREVIOUS);
				progressBar.setProgress(0);
			}
		});
		imgBtn_PlayOrPause.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				/*
				if (player != null && player.isPlaying()) {
					pause();
					imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_play);
				} else {
					play(number);
					imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
				}
				*/
				Log.d("当前状态", String.valueOf(status));
				switch (status){
					case MusicService.STATUS_PLAYING:
						sendBroadcastOnCommand(MusicService.COMMAND_PAUSE);
                        imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_play);
						Log.d("playOrPause按钮被按下", "状态为Playing,暂停");
						break;
					case MusicService.STATUS_PAUSED:
						sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                        imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
						Log.d("playOrPause按钮被按下", "状态为Paused,继续");
						break;
					case MusicService.STATUS_STOPPED:
						sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                        imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
						Log.d("playOrPause按钮被按下", "状态为Stopped,播放");
						break;
					default:
						break;
				}
			}
		});
		imgBtn_Stop.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				//stop();
				imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_play);
				sendBroadcastOnCommand(MusicService.COMMAND_STOP);
				Log.d("playOrPause是否可用", String.valueOf(imgBtn_PlayOrPause.isEnabled()));
			}
		});
		imgBtn_Next.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				//moveNumberToNext();
				//play(number);
				imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
				if(playmode==MainActivity.MODE_RANDOM) sendBroadcastOnCommand(MusicService.COMMAND_RANDOM);
				else sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
				progressBar.setProgress(0);
			}
		});
		list.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			    //i=0;
				//number = position;
				//play(number);
				imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
				number = position;
				sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
			}
		});
//		player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
//            @Override
//            public void onCompletion(MediaPlayer mediaPlayer) {
//
////                if((number ) < MusicList.getMusicList().size()-1){
////                    sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
////                }
////                else {
////                    Toast.makeText(MainActivity.this,"列表播放完成",Toast.LENGTH_SHORT).show();
////                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_play);
////                }
//            }
//        });
		progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i2, boolean b) {
                Log.d("b的值",  String.valueOf(b));
                if(b){
                    i=i2;
                    //player.seekTo(i*1000);
					imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
					//play(number);
					sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
		menuBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				openOptionsMenu();
			}
		});
	}
	public void openOptionsMenu(){
		super.openOptionsMenu();
	}
	private void initMusicList() {
		musicArrayList = MusicList.getMusicList();
		if(musicArrayList.isEmpty())
		{
			Cursor mMusicCursor = this.getContentResolver().query(
					MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
					MediaStore.Audio.AudioColumns.TITLE);
			int indexTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
			int indexArtist = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
			int indexTotalTime = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);
			int indexPath = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);


			for (mMusicCursor.moveToFirst(); !mMusicCursor.isAfterLast(); mMusicCursor
					.moveToNext()) { 
				String strTitle = mMusicCursor.getString(indexTitle);
				String strArtist = mMusicCursor.getString(indexArtist);
				String strTotoalTime = mMusicCursor.getString(indexTotalTime);
				String strPath = mMusicCursor.getString(indexPath);

				if (strArtist.equals("<unknown>"))
					strArtist = "未知歌手";
				Music music = new Music(strTitle, strArtist, strPath, strTotoalTime);
				musicArrayList.add(music);
			}
		}
	}
	private void initListView() {
	    //初始化歌单（这里hashMap相当于js的{}对象）
		List<Map<String, String>> list_map = new ArrayList<Map<String, String>>();
		HashMap<String, String> map;
		SimpleAdapter simpleAdapter;
		for (Music music : musicArrayList) {
			map = new HashMap<String, String>();
			map.put("musicName", music.getmusicName());
			map.put("musicArtist", music.getmusicArtist());
			list_map.add(map);
		}
		String[] from = new String[] { "musicName", "musicArtist" };
		int[] to = { R.id.listview_tv_title_item, R.id.listview_tv_artist_item };
		simpleAdapter = new SimpleAdapter(this, list_map, R.layout.listview,from, to);
		list.setAdapter(simpleAdapter);
	}
	private void checkMusicfile()
	{
	    //播放使能
		if (musicArrayList.isEmpty()) {
			imgBtn_Next.setEnabled(false);
			imgBtn_PlayOrPause.setEnabled(false);
			imgBtn_Previous.setEnabled(false);
			imgBtn_Stop.setEnabled(false);
			Toast.makeText(getApplicationContext(), "歌单为空",Toast.LENGTH_SHORT).show();
		} else {
			imgBtn_Next.setEnabled(true);
			imgBtn_PlayOrPause.setEnabled(true);
			imgBtn_Previous.setEnabled(true);
			imgBtn_Stop.setEnabled(true);
		}
	}
	private void sendBroadcastOnCommand(int command){
		Intent intent = new Intent(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
		intent.putExtra("command",command);
		switch (command){
			case MusicService.COMMAND_PLAY:
				intent.putExtra("number",number);
				break;
			case MusicService.COMMAND_SEEK_TO:
				intent.putExtra("seek",i);
				break;
			default:
				break;
		}
		sendBroadcast(intent);
	}
	class StatusChangeReceiver extends BroadcastReceiver{
		public void onReceive(Context context, Intent intent){
			String musicName=intent.getStringExtra("musicName");
			String musicArtist=intent.getStringExtra("musicArtist");
			status=intent.getIntExtra("status",-1);
			switch (status){
				case MusicService.STATUS_PLAYING:
					imgBtn_PlayOrPause.setBackgroundResource(R.drawable.pause);
					textView.setText("正在播放:"+musicName+" - "+musicArtist);
					break;
				case MusicService.STATUS_PAUSED:
					textView.setText("已暂停:"+musicName+" - "+musicArtist);
					break;
				case MusicService.STATUS_STOPPED:
					imgBtn_PlayOrPause.setBackgroundResource(R.drawable.play);
					textView.setText("GracePlayer");
					break;
				case MusicService.STATUS_COMPLETED:
					//sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
					textView.setText("GracePlayer");
					int n=intent.getIntExtra("playingNumber",0);
					switch (playmode){
						case MODE_LIST_SEQUENCE:
							if(n==MusicList.getMusicList().size()-1){
								sendBroadcastOnCommand(MusicService.STATUS_STOPPED);
							}else {
								sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
							}
							break;
						case MainActivity.MODE_SINGLE_CYCLE:
							sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
							break;
						case MainActivity.MODE_LIST_CYCLE:
							sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
							break;
						case MainActivity.MODE_RANDOM:
							sendBroadcastOnCommand(MusicService.COMMAND_RANDOM);
							break;
						default:break;
					}
					break;
				default:
					break;
			}
		}
	}
	class seekBarChangedReceiver extends BroadcastReceiver{
		public void onReceive(Context context,Intent intent){
			int progress=intent.getIntExtra("progress",0);
			String playedTimeTag=intent.getStringExtra("playedTime");
			progressBar.setProgress(progress);
			if(playedTimeTag!="") playedTime.setText(playedTimeTag);
			else playedTime.setText("00:00");
		}
	}
	class musicChangedReceiver extends BroadcastReceiver{
		public void onReceive(Context context,Intent intent){
			int max=intent.getIntExtra("duration",0);
			progressBar.setMax(max);
			musicTimeText.setText((max/60<10?"0":"")+String.valueOf(max/60)+":"+(max%60<10?"0":"")+String.valueOf(max%60));
			Log.d("duration的值", String.valueOf(max));
		}
	}
	private void bindStatusChangedReceiver(){
		receiver=new StatusChangeReceiver();
		receiver2=new seekBarChangedReceiver();
		receiver3=new musicChangedReceiver();
		IntentFilter filter=new IntentFilter(MusicService.BROADCAST_MUSICSERVICE_UPDATE_STATUS);
		IntentFilter filter2=new IntentFilter(MusicService.BROADCAST_MUSICSERVICE_UPDATE_PROGRESS);
		IntentFilter filter3=new IntentFilter(MusicService.BROADCAST_MUSICSERVICE_MUSIC_STATUS);
		registerReceiver(receiver,filter);
		registerReceiver(receiver2,filter2);
		registerReceiver(receiver3,filter3);
	}
	public boolean onKeyDown(int keyCode,KeyEvent event){
		int progress;
		switch (keyCode){
			case KeyEvent.KEYCODE_BACK:
				exitByDoubleClick();
				break;
			case KeyEvent.KEYCODE_VOLUME_DOWN:
				progress = seekbar_vol.getProgress();
				if(progress != 0)
					seekbar_vol.setProgress(progress-1);
				return true;
			case KeyEvent.KEYCODE_VOLUME_UP:
				progress = seekbar_vol.getProgress();
				if(progress != seekbar_vol.getMax())
					seekbar_vol.setProgress(progress+1);
				return true;
		}
		return false;
	}
	public void exitByDoubleClick(){
		Timer timer=null;
		if(!isExit){
			isExit=true;
			Toast.makeText(this,"再按一次返回键退出",Toast.LENGTH_SHORT).show();
			timer=new Timer();
			timer.schedule(new TimerTask() {
				@Override
				public void run() {
					isExit=false;
				}
			},2000);
		}else {
			System.exit(0);
		}
	}
	private void audio_Control() {
		final AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
		this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
		final int max_progress = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		seekbar_vol.setMax(max_progress);
		int progress = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		seekbar_vol.setProgress(progress);
		tv_vol .setText("音量： "+(progress*100/max_progress)+"%");
		seekbar_vol.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
			@Override
			public void onStopTrackingTouch(SeekBar arg0) {
				// TODO Auto-generated method stub
			}
			@Override
			public void onStartTrackingTouch(SeekBar arg0) {
				// TODO Auto-generated method stub
			}
			@Override
			public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
				// TODO Auto-generated method stub
				tv_vol .setText("音量： "+(arg1*100)/(max_progress)+"%");
				audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, arg1, AudioManager.FLAG_PLAY_SOUND);
			}
		});
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		sendBroadcastOnCommand(MusicService.COMMAND_CHECK_IS_PLAYING);
		PropertyBean property = new PropertyBean(MainActivity.this);
		String theme = property.getTheme();
		setTheme(theme);
		audio_Control();
		if(sleepmode == MainActivity.ISSLEEP) iv_sleep.setVisibility(View.VISIBLE);
		else iv_sleep.setVisibility(View.INVISIBLE);
	}
	private void showSleepDialog()
	{
		final View userview = this.getLayoutInflater().inflate(R.layout.dialog, null);
		final TextView tv_minute = (TextView)userview.findViewById(R.id.dialog_tv);
		final Switch switch1 = (Switch)userview.findViewById(R.id.dialog_switch);
		final SeekBar seekbar = (SeekBar)userview.findViewById(R.id.dialog_seekbar);
		tv_minute.setText("睡眠于:"+sleepminute+"分钟");

		if(sleepmode == MainActivity.ISSLEEP) switch1.setChecked(true);
		seekbar.setMax(60);
		seekbar.setProgress(sleepminute);
		seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
			@Override
			public void onStopTrackingTouch(SeekBar arg0) {
				// TODO Auto-generated method stub
			}
			@Override
			public void onStartTrackingTouch(SeekBar arg0) {
				// TODO Auto-generated method stub
			}
			@Override
			public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
				// TODO Auto-generated method stub
				sleepminute = arg1;
				tv_minute.setText("睡眠于:"+sleepminute+"分钟");
			}
		});
		switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				// TODO Auto-generated method stub
				sleepmode = arg1;
			}
		});
		final TimerTask timerTask = new TimerTask() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				System.exit(0);
			}
		};
		final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle("选择睡眠时间(0~60分钟)");
		dialog.setView(userview);
		dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				arg0.dismiss();
			}
		});
		dialog.setNeutralButton("重置", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				if(sleepmode == MainActivity.ISSLEEP)
				{
					timerTask.cancel();
					timer_sleep.cancel();
				}
				sleepmode = MainActivity.NOTSLEEP;
				sleepminute = 20;
				iv_sleep.setVisibility(View.INVISIBLE);
			}
		});
		dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				if(sleepmode == MainActivity.ISSLEEP)
				{
					timer_sleep = new Timer();
					int time =seekbar.getProgress();
					timer_sleep.schedule(timerTask, time*60*1000);
					iv_sleep.setVisibility(View.VISIBLE);
				}
				else
				{
					timerTask.cancel();
					if(timer_sleep != null) timer_sleep.cancel();
					arg0.dismiss();
					iv_sleep.setVisibility(View.INVISIBLE);
				}
			}
		});
		dialog.show();
	}
	/*
	@Override
	protected void onResume(){
		super.onResume();
		sendBroadcastOnCommand(MusicService.COMMAND_CHECK_IS_PLAYING);
		PropertyBean property=new PropertyBean(MainActivity.this);
		String theme=property.getTheme();
		setTheme(theme);
	}

	private void load(int number) {
		try {
			player.reset();
			player.setDataSource(MusicList.getMusicList().get(number).getmusicPath());
			player.prepare();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private void play(int number) {
		if (player != null && player.isPlaying()) {
			player.stop();
		}
		load(number);
        first=false;
		int x=player.getDuration()/1000;
        progressBar.setMax(x);
        musicTimeText.setText((x/60<10?"0":"")+String.valueOf(x/60)+":"+(x%60<10?"0":"")+String.valueOf(x%60));
        updateBarHandler.removeCallbacks(updateThread);
        player.seekTo(i*1000);
        updateBarHandler.post(updateThread);
		player.start();
	}
	//切换下一首或上一首后，计时器双倍计数，点击暂停再开始后恢复正常bug
	private void pause() {
		if (player.isPlaying()) {
		    updateBarHandler.removeCallbacks(updateThread);
			player.pause();
		}
	}
	private void stop() {
        updateBarHandler.removeCallbacks(updateThread);
        playedTime.setText("00:00");
        progressBar.setProgress(0);
        i=0;
	    player.stop();
	}
	private void resume() {
        updateBarHandler.removeCallbacks(updateThread);
		player.start();
	}
	private void replay() {
        updateBarHandler.removeCallbacks(updateThread);
        i=0;
		player.start();
	}

	private void moveNumberToNext() {
		if ((number ) == MusicList.getMusicList().size()-1) {
			Toast.makeText(MainActivity.this,MainActivity.this.getString(R.string.tip_reach_bottom),Toast.LENGTH_SHORT).show();
			number=0;
		} else {
		    ++number;
		}
		updateBarHandler.removeCallbacks(updateThread);
		i=0;
		play(number);
	}
	private void moveNumberToPrevious() {
		if (number == 0) {
			Toast.makeText(MainActivity.this,MainActivity.this.getString(R.string.tip_reach_top),Toast.LENGTH_SHORT).show();
			number = MusicList.getMusicList().size()-1;
		} else {
			--number;
		}
        updateBarHandler.removeCallbacks(updateThread);
        i=0;
		play(number);
	}


    Handler updateBarHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            progressBar.setProgress(msg.arg1);
        }
    };
	Runnable updateThread=new Runnable() {
        @Override
        public void run() {
            i=i==0?0:i;
            if(!first) first=true;
            else i++;
            System.out.println("Begin Thread");
            Log.d("时间tag", String.valueOf(i));
            playedTime.setText((i/60<10?"0":"")+String.valueOf(i/60)+":"+(i%60<10?"0":"")+String.valueOf(i%60));
            //新建updateBarHandler的Message对象
            Message msg=updateBarHandler.obtainMessage();
            msg.arg1=i;
            updateBarHandler.sendMessage(msg);
            if(i==progressBar.getMax()){
                i=0;
                progressBar.setProgress(i);
                updateBarHandler.removeCallbacks(updateThread);
            }else{updateBarHandler.postDelayed(updateThread,1000);}
            //进度条进度持续增加
        }
    };
	*/
}

/*
UI

*/